package com.ce.pms.house.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.model.SysrefcodeDO;
import com.ce.pms.common.util.UpLoadFile;
import com.ce.pms.exception.UILayerException;
import com.ce.pms.house.service.IAreaService;
import com.ce.pms.house.service.ICoWorkerService;
import com.ce.pms.house.service.IProjectService;
import com.ce.pms.house.vo.AreaVO;
import com.ce.pms.house.vo.BuildingVO;
import com.ce.pms.house.vo.CoWorkerVO;
import com.ce.pms.house.vo.ImageVO;
import com.ce.pms.house.vo.LayoutVO;
import com.ce.pms.house.vo.ProjectVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.annotation.Scope;


public class AreaAction extends PmsBaseAction {
   private final String AREA_VO_SAVE_SESSION = "areavo";
   private IAreaService areaService;
   private ICoWorkerService coWorkerService = null;
   private IProjectService projectService = null;

   public void setAreaService(IAreaService areaService) {
	this.areaService = areaService;
   }

   /**
   * Function:初始化楼盘资料页面.在显示期数资料和楼盘资料两个标签时，要求判断是否有期数。
   * 		  在显示楼盘详细资料时，需要areavo的详细信息，所以这里查询到areavo保存到session中。在显示详细信息后，清空该VO
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-6-25
   * Edit author:
   * Edit on:
   * Why:
    */
   public String initAreaBaseMain(@Read(key="areaId")Long areaId){
	   setAttribute("areaId", areaId);
	   AreaVO areaVO = areaService.findAreaById(areaId);
	   setAttribute("areavo", areaVO);
	   return "areaBaseMain";
   }

   /**
   * Function:初始化楼盘资料显示页面。
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-6-25
   * Edit author:
   * Edit on:
   * Why:
    */
   public String initAreaInformation(@Read(key="areaId")Long areaId){
	   AreaVO areaVO = areaService.findAreaById(areaId);
	   ImageVO imagevo = areaVO.getTrafficImage();

	   setAttribute("areavo", areaVO);
	   return "areaInformation";
   }
   /**
   * Function:初始化楼盘修改页面
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-6-26
   * Edit author:
   * Edit on:
   * Why:
    */
   public String initAreaBaseEdit(@Read(key="areaId")Long areaId){
	   AreaVO areavo = areaService.findAreaById(areaId);
	   setObject2Session(areavo);
	   setProjectToSession();
	   return "areaBaseEdit";
   }
   /********修改期数**********/
   /**
    * Function:初始化楼盘基本资料修改页面
    * @param
    * @return
    * Create author:yixianjian
    * Create on:2008-6-26
    * Edit author:
    * Edit on:
    * Why:
     */
   public String initAreaBaseInformationEdit(){
	   	AreaVO areavo = getObjectFSession();
	   	if(areavo != null){
	   		ImageVO imagevo = areavo.getTrafficImage();
	   	}
	   return "areaBaseInformationEdit";
   }
   /**
   * Function:初始化政府关系页面
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-7-7
   * Edit author:
   * Edit on:
   * Why:
    */
   public String initAreaGovtRelationEdit(){
	   CoWorkerVO coWorkerVO = new CoWorkerVO();
	   coWorkerVO.setCoworkerTypeCode(SysrefcodeDO.WORKER_TYPE);
	   //查询派出所
	   coWorkerVO.setCoworkerTypeValue(SysrefcodeDO.CS_CO_WORKER_TYPE_POLICE);
	   List policeStationList = coWorkerService.queryAllCoWorkerByCoWorkerType(coWorkerVO);
	   setAttribute("policeStationList", policeStationList);
	   //查询街道办
	   coWorkerVO.setCoworkerTypeValue(SysrefcodeDO.CS_CO_WORKER_TYPE_STREET);
	   List streetOrgList = coWorkerService.queryAllCoWorkerByCoWorkerType(coWorkerVO);
	   setAttribute("streetOrgList", streetOrgList);
	   //查询居委会
	   coWorkerVO.setCoworkerTypeValue(SysrefcodeDO.CS_CO_WORKER_TYPE_RESIDENT);
	   List bottomOrgList = coWorkerService.queryAllCoWorkerByCoWorkerType(coWorkerVO);
	   setAttribute("bottomOrgList", bottomOrgList);

	   return "areaGovtRelation";
   }

   /**
    * 功能描述: 在楼盘页面，不分期开发时，可以编辑配套设施，该配套设施和默认的期数有关。该方法把默认的配套设施保存到session中 <br>
    * @return
    * Create author:yixianjian <br>
    * Create on:2008-7-23  <br>
    * Edit author:  <br>
    * Edit on:    <br>
    * Why:     <br>
    */
   public String initAreaEnvironment(){
	   return "areaEnvironment";
   }

   public String initAreaJoin(){
	   return "areaJion";
   }


   /**
    * 更新楼盘基本资料
 * @throws Throwable
    *
    */
   public String editBase() {
	   UpLoadFile upload=new UpLoadFile();
	   ImageVO imagevo = null;
	   try{
		    AreaVO areavo = new AreaVO();
			List<ImageVO> imagelist = upload.parseFormAndUpload(getRequest(), areavo);
			if(imagelist != null && imagelist.size() >0){
				imagevo = imagelist.get(0);
			}
			imagevo = upload.wrapImage("trafficImage", imagevo);
			imagevo.setCreator(super.getUserId());
			areavo.setTrafficImage(imagevo);
			areavo.setHasMoreProject((areavo.getHasMoreProject() == null)?"0":"1");
			areavo.setAreaModifier(super.getUserId());
			setIsEdit(areavo);
			setIsSave(areavo);
			areavo = areaService.editBase(areavo);
			//保存到session中
			setObject2Session(areavo);
			setProjectToSession();
	   }catch(Throwable exception){
		   exception.printStackTrace();
		   if(imagevo != null)
			   upload.deleteFile(imagevo.getPath(), imagevo.getName());
	   }
		return "areaBaseInformationEdit";
   }

/**
   * Function:修改建设规划
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-7-3
   * Edit author:
   * Edit on:
   * Why:
    */
   public String editLayout(@Read LayoutVO layoutvo) {
	   setIsEdit();
	   setIsSave();
	   AreaVO areavo = getObjectFSession();
	   areavo.setLayout(layoutvo);
	   areavo = areaService.editLayout(areavo);
	   setObject2Session(areavo);
	   return "areaLayoutEdit";
   }

	/**
	 * 修改政府关系
	 * @author yixianjian
	 * Create on:2008-5-27
	 * @param
	 * @return 返回页面
	 */
   public String editGovtRelation(@Read(key="policeStationID")Long policeStationID,
		   						  @Read(key="streetOrgID")Long streetOrgID,
		   						  @Read(key="bottomOrgID") Long bottomOrgID){
	   AreaVO areavo = getObjectFSession();
	   areavo.setPoliceStation(buildCoWorkerVO(policeStationID));
	   areavo.setStreetOrg(buildCoWorkerVO(streetOrgID));
	   areavo.setBottomOrg(buildCoWorkerVO(bottomOrgID));
	   areavo =  areaService.editGovtRelation(areavo);
	   setObject2Session(areavo);
	   //设置标识
	   setIsEdit();
	   setIsSave();
	   return "editGovtRelation";
   }

   /**
   * Function:创建政府关系
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-7-9
   * Edit author:
   * Edit on:
   * Why:
    */
   private CoWorkerVO buildCoWorkerVO(Long coWorkerID){
	   if(coWorkerID == null)
		   return null;
	   CoWorkerVO coworkervo = new CoWorkerVO();
	   coworkervo.setCoWorkerID(coWorkerID);
	   return coworkervo;
   }
	/**
	 * 判断是否允许修改"楼盘分期开发"设置
	 * @author yixianjian
	 * Create on:2008-5-27
	 * @param
	 * @return 返回页面
	 */
   public void changeHasMoreProject() {
	   String flag = "true";
	   AreaVO areavo = getObjectFSession();
	   try{
		   areaService.ifAllowMerge(areavo);
	   }catch(Exception bizException){
		   flag = "false";
	   }
	   renderText(flag);
   }

   /**
    * 算法描述:存储AreaVO到Session
    *
    */
   private void setObject2Session(AreaVO areaVO) {
	   checkNull(areaVO);
	   AreaVO cacheAreaVO = getObjectFSession();
	   if(cacheAreaVO == null){
		   setAttribute(AREA_VO_SAVE_SESSION,areaVO, Scope.SESSION);
		   return;
	   }

	   if(areaVO.getAddress() != null)
		   cacheAreaVO.setAddress(areaVO.getAddress());
	   if(areaVO.getTrafficImage() != null)
		   cacheAreaVO.setTrafficImage(areaVO.getTrafficImage());
	   if(areaVO.getHasMoreProject() != null)
		   cacheAreaVO.setHasMoreProject(areaVO.getHasMoreProject());
	   if(areaVO.getLayout() != null)
		   cacheAreaVO.setLayout(areaVO.getLayout());
	   if(areaVO.getPoliceStation() != null)
		   cacheAreaVO.setPoliceStation(areaVO.getPoliceStation());
	   if(areaVO.getBottomOrg() != null)
		   cacheAreaVO.setBottomOrg(areaVO.getBottomOrg());
	   setAttribute(AREA_VO_SAVE_SESSION,cacheAreaVO, Scope.SESSION);
   }

   /**
    * 算法描述:从Session中获取AreaVO实例
    *
    */
   private AreaVO getObjectFSession() {
	   return (AreaVO)getAttribute(AREA_VO_SAVE_SESSION,Scope.SESSION);
   }

   /**
	 * Function:初始化房产资料设置页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-25
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
   public String initAreaMain() {
	   return "areaMain";
   }

   /**
   * Function:初始化建设规划修改页面
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-7-2
   * Edit author:
   * Edit on:
   * Why:
    */
   public String initAreaLayoutEdit(){
	   return "areaLayoutEdit";
   }

   /**
	 * Function:初始化房产资料设置页面左边的树形
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-25
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
   public void getAreaTreeData(){
	   try {
	   HttpServletResponse response = getResponse();
		response.setContentType("text/xml;charset=UTF-8");
		Element rootElement = new Element("tree");

		Document doc = new Document(rootElement);
		Attribute rootAttri = new Attribute("id", "0");
		rootElement.setAttribute(rootAttri);
		rootElement.setAttribute("select", "true");
		rootElement.setAttribute("tooltip", "根接点");

		List<Map> list = this.areaService.queryAreaBuildingTreeList();

		List<BuildingVO> buildList = null;
		AreaVO areaVO = null;

		if (!BlankUtil.isBlank(list)) {
			for (Map map : list) {
				areaVO = (AreaVO)map.keySet().toArray()[0];
				Element item = new Element("item");
				Element userDataArea= new Element("userdata");
				item.setAttribute("text", areaVO.getName());
				item.setAttribute("id", areaVO.getKeyword().toString());
				item.setAttribute("im1", "root.gif");
				item.setAttribute("im2", "root.gif");
				userDataArea.setAttribute("name", "hasMoreProject");
				userDataArea.setText(areaVO.getHasMoreProject());
				item.addContent(userDataArea);
				rootElement.addContent(item);


				buildList = (List<BuildingVO>)map.get(areaVO);

				for (BuildingVO buildingVO : buildList) {
					Element itemBuiding = new Element("item");
					Element userData= new Element("userdata");
					itemBuiding.setAttribute("id", buildingVO.getKeyword().toString());
					itemBuiding.setAttribute("aaa", "aaa");
					itemBuiding.setAttribute("text", buildingVO.getName());
					itemBuiding.setAttribute("im1", "folder.gif");
					itemBuiding.setAttribute("im2", "folder.gif");
					userData.setAttribute("name", "projectId");
					userData.setText(buildingVO.getProjectId().toString());
					itemBuiding.addContent(userData);

					item.addContent(itemBuiding);
				}

			}
		}
//		Element item = new Element("item");
//		item.setAttribute("text", "半岛城邦花园");
//		item.setAttribute("id", "001");
//		item.setAttribute("im1", "root.gif");
//		item.setAttribute("im2", "root.gif");
//		rootElement.addContent(item);
//
//
//		Element itemBuidingT = new Element("item");
//		itemBuidingT.setAttribute("id", "00102");
//		itemBuidingT.setAttribute("text", "二栋");
//		itemBuidingT.setAttribute("im1", "folder.gif");
//		itemBuidingT.setAttribute("im2", "folder.gif");
//		item.addContent(itemBuidingT);

		XMLOutputter XMLOut = new XMLOutputter();
		PrintWriter out = response.getWriter();
		XMLOut.output(doc, out);
		out.flush();

	   } catch(IOException ioe) {

	   }

   }

   /**
   * Function:如果是点击关闭按钮，先设置一个变量说明这个返回是关闭后修改的返回的页面(基本资料专用).
   * @param areavo
   * @param
   * @return
   * Create author:yixianjian
   * Create on:2008-7-3
   * Edit author:
   * Edit on:
   * Why:
    */
   	private void setIsEdit(AreaVO areavo){
   		if("isEdit".equals(areavo.getIsEdit())){
   			setAttribute("isEdit", "isEdit");
   			removeAttribute("isSave");
   		}
   	}
    /**
     * Function:如果是点击关闭按钮，先设置一个变量说明这个返回是关闭后修改的返回的页面.
     * @param areavo
     * @param
     * @return
     * Create author:yixianjian
     * Create on:2008-7-3
     * Edit author:
     * Edit on:
     * Why:
      */
  	private void setIsEdit(){
   		if("isEdit".equals(getRequest().getParameter("isEdit"))){
   			setAttribute("isEdit", "isEdit");
   			removeAttribute("isSave");
   		}
   	}
  	/**
  	* Function:点保存按钮，说明是点击保存按钮提交表单(基本资料专用)
  	* @param
  	* @return
  	* Create author:yixianjian
  	* Create on:2008-7-9
  	* Edit author:
  	* Edit on:
  	* Why:
  	 */
  	private void setIsSave(AreaVO areavo){
   		if("isSave".equals(areavo.getIsSave())){
   			setAttribute("isSave", "isSave");
   			removeAttribute("isEdit");
   		}
  	}
  	/**
  	* Function:点保存按钮，说明是点击保存按钮提交表单
  	* @param
  	* @return
  	* Create author:yixianjian
  	* Create on:2008-7-9
  	* Edit author:
  	* Edit on:
  	* Why:
  	 */
  	private void setIsSave(){
  		Boolean flag = "isSave".equals(getRequest().getParameter("isSave")) ;
  		if( flag){
  			setAttribute("isSave","isSave");
  			removeAttribute("isEdit");
  		}
  	}

  	/**
  	 * 功能描述: 设置areavo中的projectvo到session <br>
  	 *
  	 * Create author:yixianjian <br>
  	 * Create on:2008-7-23  <br>
  	 * Edit author:  <br>
  	 * Edit on:    <br>
  	 * Why:     <br>
  	 */
  	private void setProjectToSession(){
 	   checkNull(getObjectFSession());
 	   if("1".equals(getObjectFSession().getHasMoreProject()))
 		   return;
 	   List<ProjectVO> projectList =  projectService.getProjectVoListByAreaId(getObjectFSession().getKeyword());
	   //判断是否数据是否出现异常，在楼盘下面需要修改配套设施、政府关系，都是在默认期数下操作。
 	   if(projectList == null || projectList.isEmpty() || projectList.size() != 1)
		   throw new UILayerException("house:house_number_error_exception");

	   ProjectVO projectvo =  projectList.iterator().next();
	   setAttribute(ProjectAction.PROJECTVO, projectvo,Scope.SESSION);

	   setAttribute("isArea", "true",Scope.SESSION);
  	}

  	private void checkNull(Object obj){
  		if(obj == null)
  			throw new UILayerException("Parm cann't null");
  	}
	public void setCoWorkerService(ICoWorkerService coWorkerService) {
		this.coWorkerService = coWorkerService;
	}

	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}
}
